import { Layout, List, DatePicker, message, Input, Tooltip, Empty,  Typography} from 'antd';
import dayjs from 'dayjs';
import { useState, useEffect, useRef } from 'react';
import { useContextSelector } from 'use-context-selector';

import { SvgIcon } from '@/components/icon';
import useInitialize from '@/hooks/event/use-initialize';
import { logout } from '@/pages/auth/authUtils';
import { useUserInfo } from '@/store/userStore';
import { useThemeToken } from '@/theme/hooks';

import { ChatContext } from '../context';
import '../styles/chat.css';

const { RangePicker } = DatePicker;


import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';

import Title from 'antd/es/skeleton/Title';
import VirtualList from 'rc-virtual-list';


import { useChatActions } from '@/store/chatStore';

import { getHistoriesRes } from '@/common/types';
import { removeRefTags } from '@/utils/regexRules';


const { Sider } = Layout;

const LeftSidebar = ({ onClose,hisList,handleHisItem,nextHisList }) => {
  const { colorPrimary } = useThemeToken();
  const { username, role } = useUserInfo();
  const [isHovered, setIsHovered] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  // const [isClickTriggered, setIsClickTriggered] = useState(false);
  const {
    isClickTriggered,
    setIsClickTriggered
  } = useContextSelector(
    ChatContext,
    (s) => s,
  );

  const { setSearchQuestion } = useChatActions();

  const scrollElement = document.getElementById('scrollElement');
  // 添加滚动事件监听器
  if (scrollElement) {
    scrollElement.addEventListener('scroll', () => {
      // 获取滚动位置
      const { scrollTop } = scrollElement;

      // 获取元素的高度
      const { scrollHeight } = scrollElement;
      // 获取视口高度
      const { clientHeight } = scrollElement;
      // console.log(111111111111,scrollTop,scrollHeight,clientHeight);
      // 判断是否触底
      if (scrollTop + clientHeight + 28 >= scrollHeight) {
        console.log('触底了！');
        // 执行触底操作
        // 例如：加载更多数据
      }
    });
  }

  const ContainerHeight = `calc(100vh - 174px)`;
  // const ContainerHeight = 500;
  // useEffect

  const onScroll = (e: React.UIEvent<HTMLElement, UIEvent>) => {
    // Refer to: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#problems_and_solutions
    if (Math.abs(e.currentTarget.scrollHeight - e.currentTarget.scrollTop - e.currentTarget.clientHeight) <= 1) {
      // appendData();
      console.log('下一页');
      nextHisList()
    }
  };
  
  

  const dateFormat = 'YYYY-MM-DD';
  const today = new Date();
  const todayFormatted = dayjs(today).format(dateFormat);
  // console.log("todayFormatted=========",todayFormatted);

  const onDateChange = (e) => {
    console.log('onDateChange', e);
    const selectedDate = new Date(e);
    const filteredList = hisList.filter((item) => {
      const itemDate = new Date(item.time); // 假设 hisList 中的每个项都有一个 time 属性
      return itemDate.toDateString() === selectedDate.toDateString();
    });
    console.log('hisList=============', selectedDate, hisList, filteredList);
  };

  const { isDebug } = useInitialize();
  const [logoutVisible, setLogoutVisible] = useState(false);

  const { actId, setActId, isMessageLoading } = useContextSelector(ChatContext, (s) => s);

  useEffect(() => {
    setTimeout(() => {
      updateScroll();
      updateScrollUser();
    }, 1000);
  }, []);

  const roleRef = useRef(null);
  const textRef = useRef(null);

  const updateScroll = () => {
    const roleElement = roleRef.current;
    const textElement = textRef.current;
    if (roleElement && textElement) {
      const hasOverflow = roleElement.scrollWidth > textElement.clientWidth;
      if (hasOverflow) {
        const translateXValue = `-${
          (1 - textElement.clientWidth / roleElement.scrollWidth) * 100
        }%`;
        roleElement.style.animation = `scrollText 10s linear infinite`;
        roleElement.style.setProperty('--translateXValue', translateXValue);
      } else {
        roleElement.style.animationPlayState = 'paused';
      }
    }
  };

  const userNameRef = useRef(null);
  const userNameTextRef = useRef(null);

  const updateScrollUser = () => {
    const roleElement = userNameRef.current;
    const textElement = userNameTextRef.current;
    if (roleElement && textElement) {
      const hasOverflow = roleElement.scrollWidth > textElement.clientWidth;
      if (hasOverflow) {
        const translateXValue = `-${
          (1 - textElement.clientWidth / roleElement.scrollWidth) * 100
        }%`;
        roleElement.style.animation = `scrollText 10s linear infinite`;
        roleElement.style.setProperty('--translateXValue', translateXValue);
      } else {
        roleElement.style.animationPlayState = 'paused';
      }
    }
  };

  const handleLogoutCancel = () => {
    setLogoutVisible(false);
  };

  const itemCli = (item) =>{
      if (isMessageLoading) {
        message.info("对话生成中，暂不支持查看历史会话内容")
        return
      }
      console.log(item);
      setIsClickTriggered(true)

      handleHisItem(item)
      setActId(item.id)
  }
    

    useEffect(() => {
      if (actId && !isClickTriggered) {
        const element = document.getElementById(`item-${actId}`);
        console.log(element);
        
        if (element) {
          element.scrollIntoView({ behavior: 'smooth', block:'center' });
          
        }
      }

      setIsClickTriggered(false)
    }, [actId,isClickTriggered]);

  return (
    <>
      <Sider
        width={300}
        style={{
          background: '#FBFCFFB2',
          padding: '20px',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
          position: 'relative',
          border: '1px solid',
          borderImageSource:
            'linear-gradient(157.24deg, #FFFFFF 9.04%, rgba(255, 255, 255, 0.89) 99.14%)',
        }}
      >
        <div>
          {/* Logo and Close Button */}
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: '20px',
            }}
          >
            <SvgIcon icon="ic-logo-mini" size="40" />

            <div
              // className="ml-10 cursor-pointer rounded-full border border-solid border-gray-300 p-2"
              className="ml-10 cursor-pointer"
              style={{ zIndex: 10 }}
              onClick={() => {
                onClose & onClose();
              }}
            >
              {/* <MenuFoldOutlined style={{ fontSize: '20px' }} /> */}
              <SvgIcon icon="ic_rj_sidebar_close" size="40" />
            </div>
          </div>
        </div>

        <div>
          <Input.Search placeholder="搜索" allowClear={true} onSearch={(val)=>{setSearchQuestion(val)}} style={{ width: '100%' }} />
        </div>

        {/* Card List */}
        <div
          style={{
            borderRadius: '10px',
            // background: 'linear-gradient(107.03deg, #E7DCFF -11.11%, #FEFBFF 56.31%)',
            // border: '2px solid #A791FF',
            height: 'calc(100vh - 155px)',
            position: 'relative',
            overflowY: 'scroll',
            overflowX: 'hidden',
            scrollbarWidth: 'none',
            marginTop:'10px',
          }}
          onScroll={onScroll}
        >
          <List>
            {
              hisList?.length > 0 ?
              <VirtualList
                data={hisList}
                // height={ContainerHeight}
                // itemHeight={47}
                itemKey="time"
              >
                {(item: any) => (
                  <div style={{ width: '100%' }}>
                    <div style={{height:'30px',lineHeight:'30px',fontSize:'18px',position:'sticky',top:'0px',zIndex:"100",backgroundColor: '#FBFCFF'}} className='font-bold mb-3 pl-4'>{item.time == todayFormatted ? '今天':item.time}</div>
                    
                        <List
                          locale={{
                            emptyText: '暂无历史会话',
                          }}
                          className="demo-loadmore-list"
                          loading={false}
                          itemLayout="horizontal" 
                          dataSource={item?.child}
                          renderItem={(item: getHistoriesRes) => (
                            <List.Item
                              id={`item-${item.id}`}
                              onClick={() =>itemCli(item)}
                              className={`cursor-pointer  hover:bg-gray-300  ${actId === item.id ? 'bg-gray-300' : ''}`}
                              style={{
                                // backgroundColor: '#EDEFF7',
                                // background:'linear-gradient(to bottom right, #FFFBFF 0%, #E0E2F9 100%)',
                                // height: '40px',
                                borderRadius: '10px',
                                border: '1px solid #EDEFF7',
                                margin: '5px',
                                padding: '5px 10px',
                                display: 'flex',
                                flexDirection: 'column', alignItems: 'flex-start'
                                // justifyContent: 'space-between',
                                // alignItems: 'center',
                              }}
                            >
                              <div
                                className={`cursor-pointer hover:text-purple  ${actId === item.id ? 'text-purple' : ''}`}
                                style={{
                                  width:'100%',
                                  height: item?.highlight_content?'unset':'40px',
                                  lineHeight: item?.highlight_content?'unset':'40px',
                                  flex: 1,
                                  overflow: 'hidden',
                                  whiteSpace: 'nowrap',
                                  textOverflow: 'ellipsis',
                                  fontWeight: item?.highlight_content?'700':'unset',
                                  display: 'flex'
                                }}
                              >
                                <div style={{marginRight:'5px'}}> 📑 </div>
                                {removeRefTags(item.title)}
                              </div>
                              {
                                item?.highlight_content &&
                                <Tooltip title={removeRefTags(item?.highlight_content)}>
                                  <div
                                    style={{
                                      width:'100%',
                                      flex: 1,
                                      overflow: 'hidden',
                                      whiteSpace: 'nowrap',
                                      textOverflow: 'ellipsis',
                                      fontSize: '12px',
                                      marginTop: '5px'
                                    }}
                                  >
                                    {removeRefTags(item?.highlight_content)}
                                  </div>
                                </Tooltip>
                              }
                            
                            </List.Item>
                          )}
                        />

                  </div>
                )}
              </VirtualList>
              :
              <Empty description={<Typography.Text>暂无历史会话</Typography.Text>} />
            }
          </List>
          
          
          
        </div>

        {/* User Info */}
        {/* <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            position: 'absolute',
            bottom: '20px',
            left: '20px',
            right: '20px',
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Avatar
              className="h-10 w-10 transform-none cursor-pointer px-0 hover:scale-105"
              style={{ backgroundColor: colorPrimary }}
            >
              {username ? username[0] : ''}
            </Avatar>
            <div style={{ paddingLeft: '10px', width: '150px' }}>
              <div
                style={{
                  maxWidth: '150px',
                  fontSize: '16px',
                  fontWeight: 'bold',
                  msOverflowStyle: 'none',
                  whiteSpace: 'nowrap',
                  scrollbarWidth: 'none',
                  // overflowX: 'scroll',
                }}
              >
                <div className="scrollable-text" ref={userNameTextRef}>
                  <span ref={userNameRef}>{username}</span>
                </div>
              </div>
              <div
                style={{
                  maxWidth: '150px',
                  fontSize: '12px',
                  color: '#666',
                  msOverflowStyle: 'none',
                  whiteSpace: 'nowrap',
                  overflowX: 'hidden',
                }}
              >
                <div
                  className={`scrollable-text ${isDebug ? 'cursor-pointer' : ''}`}
                  ref={textRef}
                  onClick={() => {
                    isDebug && setIsModalOpen(true);
                  }}
                >
                  <span ref={roleRef}>{role?.name}</span>
                </div>
              </div>
            </div>
          </div>
          <Button
            type="text"
            onClick={() => {
              setLogoutVisible(true);
            }}
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
          >
            {isHovered ? '退出' : <RightOutlined />}
          </Button>
        </div> */}
      </Sider>

      {/* <RoleSwitchModal
        open={isModalOpen}
        onOk={() => {
          setIsModalOpen(false);
        }}
        onCancel={() => setIsModalOpen(false)}
      /> */}

      {/* <DeleteConfirmModal
        visible={logoutVisible}
        text="确定要退出登录吗?"
        onCancel={handleLogoutCancel}
        onConfirm={handleLogoutConfirm}
        onConfirmText="退出登录"
      /> */}
    </>
  );
}

export default LeftSidebar;
